package com.gdufe.studytogether.controller;

import com.gdufe.studytogether.domain.R;
import com.gdufe.studytogether.domain.pojo.User;
import com.gdufe.studytogether.domain.vo.UserAddVO;
import com.gdufe.studytogether.mapper.UserMapper;
import com.gdufe.studytogether.service.user.UserService;
import com.gdufe.studytogether.utils.UserThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;

    @PostMapping("/login")
    @CrossOrigin
    public R login(@RequestBody User uservo,HttpServletRequest request){
        User userLogin = (User)request.getSession().getAttribute("userLogin");
        if(userLogin!=null){
            return R.ok(userLogin);
        }
        String password = uservo.getPassword();
        String username = uservo.getUsername();
        User user = userService.selectByUsername(username);
        if (user==null){
            return R.error("用户不存在");
        }
        if (!user.getPassword().equals(password)){
            return R.error("密码错误");
        }
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        user.setPassword("");
        //用户信息存入
        session.setAttribute("userLogin",user);
        return R.ok(user);
    }

    @PostMapping("/regist")
    public R regist(@RequestBody User user) throws Exception {
        user.setId(null);
        user.setRoleId(2);//默认为普通用户
        boolean save = userService.save(user);
        if (!save){
            throw new Exception("注册失败");
        }
        return R.ok();
    }

    @GetMapping("/logout")
    public R logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session!=null){
            session.setAttribute("userLogin",null);
        }
       return R.ok();
    }

    @GetMapping("/getTeachers")
    public R getTeachers() throws Exception {
        List<User> teachers = userService.getTeachers();
        return R.ok(teachers);
    }

    @PostMapping("/edit")
    public R editUserInfo(@RequestBody User user) throws Exception {
        userService.edit(user);
        return R.ok();
    }

    @GetMapping("/show")
    public R showInfo(Integer id) throws Exception {
        User show = userService.show(id);
        return R.ok(show);
    }

    @GetMapping("/checklogin")
    public R showInfo(HttpServletRequest request) throws Exception {
        User user = (User) request.getSession().getAttribute("userLogin");
        if (user==null){
            return R.error("用户未登录");
        }else{
            return R.ok(user);
        }

    }


}
